#include "CustomLogSink.h"
#include <sstream>
#include <iostream>
#include <chrono>
#include <iomanip>
#include <string>
#include <codecvt>
#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
#include <thread>

CustomLogSink::CustomLogSink(const std::string& base_filename) : base_filename_(base_filename) {
    UpdateLogFile();
}

#if 0
void CustomLogSink::send(google::LogSeverity severity,  const char* full_filename,
    const char* base_filename, int line,
    const struct ::tm* tm_time,
    const char* message, size_t message_len) 
{
    std::lock_guard<std::mutex> lock(mutex_);

    // 检查是否需要更新日志文件
    UpdateLogFile();

    // 写入日志消息
    log_file_ << "[" << google::GetLogSeverityName(severity)
        << "] [" << GetCurrentTimeWithMilliseconds()<< "]["<<base_filename<<":"<<line
        << "]: " << message;
}

#else

#include <sys/syscall.h>
#include <chrono>
#include <iomanip>
#include <thread>

void CustomLogSink::send(google::LogSeverity severity, const char* full_filename,
                         const char* base_filename, int line,
                         const struct ::tm* tm_time,
                         const char* message, size_t message_len) {
    std::lock_guard<std::mutex> lock(mutex_);
    UpdateLogFile();

    // 获取微秒时间戳
    auto now = std::chrono::system_clock::now();
    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(
        now.time_since_epoch()) % 1000000;

     

    // 获取线程ID（Linux示例）
    uint64_t thread_id = syscall(SYS_gettid);

    // 格式化日志条目
    std::ostringstream log_entry;
    log_entry << google::GetLogSeverityName(severity)[0]
              << std::put_time(tm_time, "%Y%m%d %H:%M:%S")
              << "." << std::setfill('0') << std::setw(6) << microseconds.count()
              << " " << thread_id
              << " " << base_filename << ":" << line << "] " << message;

    log_file_ << log_entry.str();
}




#endif

void CustomLogSink::UpdateLogFile() {
    time_t now = time(nullptr);
    struct tm now_tm;
    localtime_r(&now, &now_tm); // 使用 localtime_r 替代 localtime_s

    if (now_tm.tm_mday != last_day_) {
        if (log_file_.is_open()) {
            log_file_.close();
        }

        std::string log_filename = base_filename_;
        log_file_.open(log_filename, std::ios_base::app);
        last_day_ = now_tm.tm_mday;
    }
}

std::string CustomLogSink::GetCurrentTimeWithMilliseconds() {
    // 获取当前系统时间点
    auto now = std::chrono::system_clock::now();

    // 转换为time_t时间类型
    auto now_as_time_t = std::chrono::system_clock::to_time_t(now);

    // 转换为tm结构
    struct tm timeinfo;
    localtime_r(&now_as_time_t, &timeinfo); // 使用 localtime_r 替代 localtime_s

    // 获取当前时间的毫秒部分
    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(
        now.time_since_epoch()) % 1000;

    // 使用wstringstream进行格式化
    std::wstringstream wss;
    wss << std::put_time(&timeinfo, L"%Y-%m-%d %H:%M:%S")
        << L'.' << std::setfill(L'0') << std::setw(3) << milliseconds.count();

    std::wstring wstr = wss.str();

    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
    return converter.to_bytes(wstr);
}
